package server

import (
	"context"
	"fmt"
	"gitee.com/madaoco/cron_node/rpc/pb"
	"gitee.com/madaoco/cron_node/utils"
	"google.golang.org/grpc"
	"log"
	"net"
	"os"
	"os/signal"
	"syscall"
)

//var keepAlivePolicy = keepalive.EnforcementPolicy{
//	MinTime:             10 * time.Second,
//	PermitWithoutStream: true,
//}
//
//var keepAliveParams = keepalive.ServerParameters{
//	MaxConnectionIdle: 30 * time.Second,
//	Time:              30 * time.Second,
//	Timeout:           3 * time.Second,
//}

type taskServer struct{}

func (t *taskServer) Run(ctx context.Context, req *pb.TaskRequest) (*pb.TaskResponse, error) {

	defer func() {
		if err := recover(); err != nil {
			log.Println(err, "recover")
		}
	}()
	output, err := utils.ExecShell(ctx, req.Command)
	var errStr string
	if err != nil {
		errStr = err.Error()
	}
	res := pb.TaskResponse{
		Output: output,
		Error:  errStr,
	}
	return &res, nil
}

func Start(addr string, tlsConfig *TlsConfig) {
	listener, err := net.Listen("tcp", addr)
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}
	//opts := []grpc.ServerOption{
	//	grpc.KeepaliveEnforcementPolicy(keepAlivePolicy),
	//	grpc.KeepaliveParams(keepAliveParams),
	//}
	var opts []grpc.ServerOption

	if tlsConfig.EnableTLS {
		tlsAuth, err := tlsConfig.makeTlsConfig()
		if err != nil {
			log.Fatalln(err)
		}
		opt := grpc.Creds(tlsAuth)
		opts = append(opts, opt)
	}

	rpcServer := grpc.NewServer(opts...)

	pb.RegisterTaskServer(rpcServer, &taskServer{})

	go func() {
		log.Println("grpc server listen on " + addr)
		if err := rpcServer.Serve(listener); err != nil {
			log.Fatalf("failed to serve: %v", err)
		}
	}()

	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM)
	for {
		s := <-c
		fmt.Println("收到信号 -- ", s)
		switch s {
		case syscall.SIGHUP:
			fmt.Println("收到终端断开信号, 忽略")
		case syscall.SIGINT, syscall.SIGTERM:
			fmt.Println("应用准备退出")
			rpcServer.GracefulStop()
			return
		}
	}
}
